﻿using Microsoft.Practices.Unity.InterceptionExtension;
using MotorLibrary.DAL;
using System;
using System.Collections.Generic;
using System.Transactions;
using System.Data.SqlClient;

namespace WebMotor
{
    public class MiInterceptionBehavior: IInterceptionBehavior
    {
        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
        }

        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            IMethodReturn resultado;
            if (MotorDbContext.Connection == null)
            {
                // Inicializa la base de datos si no existe
                using (MotorDbContext context = new MotorDbContext(new MotorDbInitializer()))
                {
                    context.Tipos.Find(1);
                }

                using (var txScope = new TransactionScope())
                {
                    using (SqlConnection sqlConnection =
                        new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MotorDb"].ToString()))
                    {
                        sqlConnection.Open();
                        MotorDbContext.Connection = sqlConnection;

                        resultado = getNext()(input, getNext);

                        if (resultado.Exception == null)
                        {
                            txScope.Complete();
                        }
                        else
                        {
                            txScope.Dispose();
                        }
                        MotorDbContext.Connection = null;
                    }
                }
            }
            else
            {
                resultado = getNext()(input, getNext);
            }

            return resultado;
        }

        public bool WillExecute
        {
            get { return true; }
        }
    }
}